﻿using COSXML;
using COSXML.Auth;
using COSXML.Model.Bucket;
using COSXML.Model.Tag;
using Md.Api.DDD;
using Md.Api.Model.Util.Oss.Request;
using Md.Api.Model.Util.Oss.Response;

namespace Md.Util.Service.Oss;
/// <summary>
/// 通过文件夹获取对象数据服务
/// </summary>
public class TencentGetObjectDataByFolderService : ApiBase<RequestTencentGetObjectDataByFolderModel>
{
    private CosXml cosXml;
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        try
        {
            //初始化 CosXmlConfig
            var bucketname = JsonConfig.JsonRead("MdTencent:Cos:BucketName");
            var appid = JsonConfig.JsonRead("MdTencent:Cos:APPID"); // 设置腾讯云账户的账户标识 APPID
            var region = JsonConfig.JsonRead("MdTencent:Cos:Region"); //设置一个默认的存储桶地域
            var secretId = JsonConfig.JsonRead("MdTencent:SecretId");
            var secretKey = JsonConfig.JsonRead("MdTencent:SecretKey");

            CosXmlConfig config = new CosXmlConfig.Builder()
              .IsHttps(true)  //设置默认 HTTPS 请求
              .SetRegion(region)  //设置一个默认的存储桶地域
              .SetDebugLog(true)  //显示日志
              .Build();  //创建 CosXmlConfig 对象

            long durationSecond = 600; //每次请求签名有效时长，单位为秒

            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);

            cosXml = new CosXmlServer(config, qCloudCredentialProvider);

            // 存储桶名称，此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
            string bucket = bucketname;
            GetBucketRequest request = new GetBucketRequest(bucket);
            //获取 a/ 下的对象以及子目录
            request.SetPrefix(Parameter.CosFolderPath);
            // request.SetDelimiter(Parameter.CosFolderPath);
            //执行请求
            GetBucketResult result = cosXml.GetBucket(request);
            //bucket的相关信息
            ListBucket info = result.listBucket;
            // 对象列表
            List<ListBucket.Contents> objects = info.contentsList;

            var fileList = new List<ResponseTencentGetObjectDataByFolderModel>();

            if (objects != null && objects.Count() > 0)
            {
                foreach (var obj in objects)
                {
                    if (obj != null && !string.IsNullOrWhiteSpace(obj.key) && obj.key != $"{Parameter.CosFolderPath}/")
                    {
                        var fileNameList = obj.key.Split("/");
                        var fileName = fileNameList[fileNameList.Length - 1];
                        var extList = fileName.Split(".");
                        var ext = extList[extList.Length - 1];
                        var objModel = new ResponseTencentGetObjectDataByFolderModel();
                        objModel.FilePath = obj.key.ToString();
                        objModel.FileName = fileName;
                        objModel.FileExt = ext;
                        objModel.ETag = obj.eTag;
                        objModel.LastModified = Convert.ToDateTime(obj.lastModified);
                        objModel.Size = obj.size;
                        objModel.Id = obj.owner.id;

                        fileList.Add(objModel);
                    }
                }
            }

            Result.Data = fileList;
            Result.Msg = "success";
        }
        catch (COSXML.CosException.CosClientException clientEx)
        {
            //请求失败
            throw new AggregateException(clientEx);
        }
        catch (COSXML.CosException.CosServerException serverEx)
        {
            //请求失败
            throw new AggregateException(serverEx.GetInfo());
        }

    }
}
